﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using Microsoft.WindowsAzure.StorageClient;
using System.Security.AccessControl;

namespace UploadBlobToAzure
{
    public partial class Form1 : Form
    {
        
        string blobEndPoint=string.Empty;
        string storageAccName = string.Empty;
        string accountKey = string.Empty;
        List<CloudBlobContainer> containerList;
        CloudBlobClient blobClient;
        CloudBlobContainer container;
        List<string> blobList=new List<string>();
        List<string> blobDirList = new List<string>();
        custom_messages customMessageForm = new custom_messages();
        CloudBlob blobtoDelete;
        List<CloudBlob> blobtoDeleteList=new List<CloudBlob>();
        List<CloudBlob> blobtoDownloadList = new List<CloudBlob>();
        List<CloudBlob> cloudBlobListforSearch=new List<CloudBlob>();
        

        public Form1()
        {
            InitializeComponent();
            txtSearch.Enabled = false;
            this.MaximizeBox = false;
            

            if (File.Exists("uploadblobtoazure.xml"))
            {
                manageBlobToolStripMenuItem.Enabled = false;
                try
                {                    
                    XmlDocument doc = new XmlDocument();
                    doc.Load("uploadblobtoazure.xml");
                    XmlNodeList xmlnl = doc.SelectNodes("xml/configuration");
                    if (!cmbStorageSelect.Items.Contains("---Select A Storage Account To Connect To---"))
                    {
                        cmbStorageSelect.Items.Add("---Select A Storage Account To Connect To---");
                    }
                    cmbStorageSelect.Text = cmbStorageSelect.Items[0].ToString();
                    foreach (XmlNode xml in xmlnl)
                    {
                        XmlNode node = xml.SelectSingleNode("storageaccount");
                        cmbStorageSelect.Items.Add(node.InnerText);
                    }
                    
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    Application.Exit();
                }
            }
            else
            {
                MessageBox.Show("Welcome!!, It seems you are here for the first Time\n, Please Go ahead and add the storage account that you wish to work with\n You Can Do so by Clikcing the \"Add Account To List\" Button");
                btnConnect.Enabled = false;
                btnEdit.Enabled = false;
                btnRemoveList.Enabled = false;
                cmbStorageSelect.Enabled = false;
                manageBlobToolStripMenuItem.Enabled = false;
                 chkSSL.Enabled = false;
                 txtSearch.Enabled = false;
                 btnDisconnect.Enabled = false;
                 
            }
        }

        private void btnAddAccount_Click(object sender, EventArgs e)
        {
            
            bool callToAddStorageForm=true;
            while (callToAddStorageForm == true)
            {
                callToAddStorageForm=callAddStorageForm();
                if (callToAddStorageForm)
                {
                    DialogResult result = MessageBox.Show("Add Another Storage Account?", "Attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        callToAddStorageForm = true;
                    }
                    else
                    {
                        callToAddStorageForm = false;
                    }
                }
                else
                {
                    callToAddStorageForm = false;
                }
            }

            if (File.Exists("uploadblobtoazure.xml"))
            {

                try
                {
                    cmbStorageSelect.Items.Clear();
                    XmlDocument doc = new XmlDocument();
                    doc.Load("uploadblobtoazure.xml");
                    XmlNodeList xmlnl = doc.SelectNodes("xml/configuration");
                    if (!cmbStorageSelect.Items.Contains("---Select A Storage Account To Connect To---"))
                    {
                        cmbStorageSelect.Items.Add("---Select A Storage Account To Connect To---");
                    }
                    cmbStorageSelect.Text = cmbStorageSelect.Items[0].ToString();
                    foreach (XmlNode xml in xmlnl)
                    {
                        XmlNode node = xml.SelectSingleNode("storageaccount");
                        cmbStorageSelect.Items.Add(node.InnerText);
                    }
                    if (cmbStorageSelect.Items.Count > 0)
                    {
                        btnConnect.Enabled = true;
                        btnEdit.Enabled = true;
                        btnRemoveList.Enabled = true;
                        cmbStorageSelect.Enabled = true;
                        //manageBlobToolStripMenuItem.Enabled = true;
                        
                        
                        chkSSL.Enabled = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    Application.Exit();
                }
            }          

        }


        public bool callAddStorageForm()
        {
            var AddStorageAccount = new AddStorageAccountToList();
            if(AddStorageAccount.ShowDialog() == DialogResult.OK)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        private void btnRemoveList_Click(object sender, EventArgs e)
        {
            bool DeleteStorageFmList = true;
            while (DeleteStorageFmList == true)
            {
                DeleteStorageFmList=DeleteStorageFromList();
                if (DeleteStorageFmList)
                {
                    DialogResult result = MessageBox.Show("Delete Another Storage Account?", "Attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        DeleteStorageFmList = true;
                    }
                    else
                    {
                        DeleteStorageFmList = false;
                    }
                }
                else
                {
                    DeleteStorageFmList = false;
                }

            } 

            try
            {
                cmbStorageSelect.Items.Clear();
                XmlDocument doc = new XmlDocument();
                doc.Load("uploadblobtoazure.xml");
                XmlNodeList xmlnl = doc.SelectNodes("xml/configuration");
                if (!cmbStorageSelect.Items.Contains("---Select A Storage Account To Connect To---"))
                {
                    cmbStorageSelect.Items.Add("---Select A Storage Account To Connect To---");
                }
                cmbStorageSelect.Text = cmbStorageSelect.Items[0].ToString();
                foreach (XmlNode xml in xmlnl)
                {
                    XmlNode node = xml.SelectSingleNode("storageaccount");
                    cmbStorageSelect.Items.Add(node.InnerText);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Application.Exit();
            }
        }

        public bool DeleteStorageFromList()
        {
            var DeleteAcctFromList = new DeleteStorageFromListForm();
            DeleteAcctFromList.setStorageAccountName(storageAccName);
            if (DeleteAcctFromList.ShowDialog() == DialogResult.OK)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            bool edStorageInfo = true;
            while (edStorageInfo == true)
            {
                edStorageInfo = editStorageInfo();
                if (edStorageInfo)
                {
                    DialogResult result = MessageBox.Show("Edit Another Storage Account?", "Attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        edStorageInfo = true;
                    }
                    else
                    {
                        edStorageInfo = false;
                    }
                }
                else
                {
                    edStorageInfo = false;
                }

            }

            try
            {
                cmbStorageSelect.Items.Clear();
                XmlDocument doc = new XmlDocument();
                doc.Load("uploadblobtoazure.xml");
                XmlNodeList xmlnl = doc.SelectNodes("xml/configuration");
                if (!cmbStorageSelect.Items.Contains("---Select A Storage Account To Connect To---"))
                {
                    cmbStorageSelect.Items.Add("---Select A Storage Account To Connect To---");
                }
                cmbStorageSelect.Text = cmbStorageSelect.Items[0].ToString();
                foreach (XmlNode xml in xmlnl)
                {
                    XmlNode node = xml.SelectSingleNode("storageaccount");
                    cmbStorageSelect.Items.Add(node.InnerText);
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Application.Exit();
            }
        }



        public bool editStorageInfo()
        {
            var editStorageInfo = new EditStorageInfo();
            if (editStorageInfo.ShowDialog() == DialogResult.OK)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void cmbStorageSelect_Click(object sender, EventArgs e)
        {
            if (cmbStorageSelect.Items.Contains("---Select A Storage Account To Connect To---"))
            {
                cmbStorageSelect.Items.Remove("---Select A Storage Account To Connect To---");
            }
        }

        
        private void uploadToBlobStorageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var uploadBlobForm = new UploadBlob();
            uploadBlobForm.setBlobList(blobDirList);
            uploadBlobForm.setBlobEndPoint(blobEndPoint);
            uploadBlobForm.setaccountKey(accountKey);
            if (uploadBlobForm.ShowDialog() == DialogResult.OK)
            {
                gridContainer.Rows.Clear();
                gridContainer.ColumnCount = 2;
                gridContainer.Columns[0].Name = "Name";
                gridContainer.Columns[1].Name = "Size";
                options.UseFlatBlobListing = true;
                blobList.Clear();
                blobDirList.Clear();
                cloudBlobListforSearch.Clear();

                pictureBoxGridView.Visible = true;

                foreach (var blobItems in container.ListBlobs())
                {
                    if (blobItems.GetType() == typeof(CloudBlobDirectory))
                    {
                        blobDirList.Add(blobItems.Uri.AbsolutePath);
                    }
                }

                foreach (CloudBlob blobItem in container.ListBlobs(options))
                {
                    var absolutePath = blobItem.Uri.AbsolutePath;
                    blobList.Add(absolutePath);
                    clpageBlob = new CloudPageBlob(blobItem);
                    var sizeLong = clpageBlob.Properties.Length;
                    if (sizeLong < 1024)
                    {
                        size = (clpageBlob.Properties.Length).ToString() + " Bytes";
                    }
                    else
                    {
                        size = ((float)(clpageBlob.Properties.Length) / 1024 / 1024).ToString() + " MB";
                    }
                    gridContainer.Rows.Add(absolutePath, size);
                    cloudBlobListforSearch.Add(blobItem);
                }

                pictureBoxGridView.Visible = false;
                gridContainer.ClearSelection();

            }
            else
            {
                //do  nothing
            }
        }


        private void downloadToLocalStorageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var downloadBlobForm = new downloadBlob();
            downloadBlobForm.setBlobList(blobList);
            downloadBlobForm.setBlobEndPoint(blobEndPoint);
            downloadBlobForm.setaccountKey(accountKey);
            if(downloadBlobForm.ShowDialog()==DialogResult.OK)
            {
                //do nothing
            }
            else
            {
                //do nothing
            }
        }


        public void changeLabelStatusForm(string str)
        {
            customMessageForm.BeginInvoke(new Action(()=>
                {
                    customMessageForm.Controls["lblMessage"].Text = str;
                }               
                ));                
        }

        private void gridContainer_MouseDown(object sender, MouseEventArgs e)
        {
            
            if (e.Button == MouseButtons.Right)
            {
                var hti = gridContainer.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    if (!((DataGridViewRow)(gridContainer.Rows[hti.RowIndex])).Selected)
                    {
                        gridContainer.ClearSelection();
                        gridContainer.Rows[hti.RowIndex].Selected = true;
                    }
                } 
                
                 
                //blobtoDelete = new CloudBlob(blobEndPoint + gridContainer.Rows[hti.RowIndex].Cells[0].Value.ToString().Substring(1));
                deleteBlobContextMenu.Show(MousePosition);
            }
            else 
            {
                //do nothing
            }
        }

        private void gridContainer_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            //MessageBox.Show(gridContainer.SelectedRows.Count.ToString());
            //gridContainer.CurrentCell = gridContainer.Rows[e.RowIndex].Cells[e.ColumnIndex];
            
            //gridContainer.Rows[e.RowIndex].Selected = true;
            //gridContainer.Focus();
        }



        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            pictureBoxGridView.Show();
            bool foundAndDeleted = false;
            string problematicBlob = string.Empty;

            foreach (DataGridViewRow row in gridContainer.SelectedRows)
            {
                blobtoDeleteList.Add(new CloudBlob(blobEndPoint + row.Cells[0].Value.ToString().Substring(1)));
            }
            
            //Int32 rowToDelete = gridContainer.Rows.GetFirstRow(DataGridViewElementStates.Selected);
           // MessageBox.Show(gridContainer.SelectedRows.Count.ToString());
            //foreach(CloudBlob blobItem in container.ListBlobs(options))
            //{
            //    if(blobItem.Uri.ToString()==blobtoDelete.Uri.ToString())
            //    {
            //        foundAndDeleted=blobItem.DeleteIfExists();
            //        break;
            //    }
            //}

            foreach(CloudBlob blobItem in blobtoDeleteList)
            {
                foreach (CloudBlob blobtoTest in container.ListBlobs(options))
                {
                    if (blobtoTest.Uri.ToString() == blobItem.Uri.ToString())
                    {
                        var fileName = blobItem.Uri.AbsolutePath.Substring(blobItem.Uri.AbsolutePath.LastIndexOf("/"));
                        var fileExtension = fileName.Substring(fileName.IndexOf(".") + 1);
                        if (!fileExtension.Equals("vhd"))
                        {
                            foundAndDeleted = blobtoTest.DeleteIfExists();

                            if (!foundAndDeleted)
                            {
                                problematicBlob = blobItem.Uri.ToString();
                                break;
                            }
                            else
                            {
                                foundAndDeleted = true;
                            }
                        }
                        else
                        {
                            //MessageBox.Show("This Blob Cannot be deleted");
                            continue;
                        }
                    }                    
                }               
            }

            pictureBoxGridView.Hide();

            if(foundAndDeleted)
            {
                MessageBox.Show("The Selected Blobs deleted successfully");
                
                gridContainer.Rows.Clear();
                gridContainer.ColumnCount = 2;
                gridContainer.Columns[0].Name = "Name";
                gridContainer.Columns[1].Name = "Size";
                blobList.Clear();
                blobDirList.Clear();
                cloudBlobListforSearch.Clear();


                pictureBoxGridView.Visible = true;
                foreach (var blobItems in container.ListBlobs())
                {
                    if (blobItems.GetType() == typeof(CloudBlobDirectory))
                    {
                        blobDirList.Add(blobItems.Uri.AbsolutePath);
                    }
                }

                //cloudBlobList = container.ListBlobs(options);

                foreach (var blobItem in container.ListBlobs(options))
                {
                    clpageBlob = new CloudPageBlob((CloudBlob)blobItem);
                    var sizeLong = clpageBlob.Properties.Length;
                    if (sizeLong < 1024)
                    {
                        size = (clpageBlob.Properties.Length).ToString() + " Bytes";
                    }
                    else
                    {
                        size = ((float)(clpageBlob.Properties.Length) / 1024 / 1024).ToString() + " MB";
                    }
                    var absolutePath = blobItem.Uri.AbsolutePath;
                    blobList.Add(absolutePath);
                    gridContainer.Rows.Add(absolutePath, size);
                    cloudBlobListforSearch.Add((CloudBlob)blobItem);
                    //gridContainer.Rows.Add(absolutePath);
                }



                if ((txtSearch.Text == string.Empty) || (txtSearch.Text == "Type A Directory Or File Name to Search"))
                {

                    foreach (var blobItem in cloudBlobListforSearch)
                    {
                        clpageBlob = new CloudPageBlob(blobItem);
                        var sizeLong = clpageBlob.Properties.Length;
                        if (sizeLong < 1024)
                        {
                            size = (clpageBlob.Properties.Length).ToString() + " Bytes";
                        }
                        else
                        {
                            size = ((float)(clpageBlob.Properties.Length) / 1024 / 1024).ToString() + " MB";
                        }
                        gridContainer.Rows.Add(blobItem.Attributes.Uri.AbsolutePath,size);
                    }

                }
                else
                {
                    foreach (var blobItem in cloudBlobListforSearch)
                    {
                        if (blobItem.Attributes.Uri.AbsolutePath.ToUpperInvariant().Contains(txtSearch.Text.ToUpperInvariant()))
                        {
                            clpageBlob = new CloudPageBlob(blobItem);
                            var sizeLong = clpageBlob.Properties.Length;
                            if (sizeLong < 1024)
                            {
                                size = (clpageBlob.Properties.Length).ToString() + " Bytes";
                            }
                            else
                            {
                                size = ((float)(clpageBlob.Properties.Length) / 1024 / 1024).ToString() + " MB";
                            }
                            gridContainer.Rows.Add(blobItem.Attributes.Uri.AbsolutePath,size);
                        }
                    }
                }

                pictureBoxGridView.Visible = false;
                gridContainer.ClearSelection();
                blobtoDeleteList.Clear();

            }
            else
            {
                MessageBox.Show("Blob :" + problematicBlob + " could not be deletd!! any further deletes will be aborted");
                blobtoDeleteList.Clear();
            }

           
        }

        private void gridContainer_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //gridContainer.ClearSelection();
            gridContainer.Rows[0].Selected = false;
        }

        private void gridContainer_SelectionChanged(object sender, EventArgs e)
        {
            if(gridContainer.SelectedRows.Count==0)
            {
                gridContainer.Rows[0].Selected = false;
            }
            else
            {
                //do nothing
            }
           // MessageBox.Show(gridContainer.SelectedRows.Count.ToString());
            //gridContainer.ClearSelection();
        }

                
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            gridContainer.Rows.Clear();
            treeContainerList.Nodes.Clear();
            blobEndPoint = string.Empty;
            storageAccName = string.Empty;
            accountKey = string.Empty;
            containerList=new List<CloudBlobContainer>();
            blobList = new List<string>();
            blobDirList = new List<string>();
            manageBlobToolStripMenuItem.Enabled = false;
            txtSearch.Enabled = false;
            chkSSL.Enabled = true;
        }

        private void downloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            blobtoDownloadList.Clear();
            foreach (DataGridViewRow row in gridContainer.SelectedRows)
            {
                blobtoDownloadList.Add(new CloudBlob(blobEndPoint + row.Cells[0].Value.ToString().Substring(1)));
            }
            var downloadBlobDirectlyForm = new downloadBlobDirectly();
            downloadBlobDirectlyForm.setToBeDeletedList(blobtoDownloadList);
            downloadBlobDirectlyForm.setBlobEndPoint(blobEndPoint);
            downloadBlobDirectlyForm.setaccountKey(accountKey);
            if (downloadBlobDirectlyForm.ShowDialog() == DialogResult.OK)
            {
                //do nothing
            }
            else
            {
                //do nothing
            }
        }    
    }
}
